package pzc.context.db.mysql;

import java.util.Properties;
import java.util.Map.Entry;
import java.util.logging.Logger;

import javax.sql.DataSource;

import pzc.context.util.ContextBinder;

import com.mysql.jdbc.jdbc2.optional.MysqlConnectionPoolDataSource;

public class MySQLContext {
	private static Logger logger = Logger.getLogger(MySQLContext.class.getName());

	public static void initContext(String jndiName, String host, String userId, String password, String schema, Properties props)
			throws Exception {

		DataSource ds = createDS(host, userId, password, schema, props);

		initContext(jndiName, ds);
	}

	public static void initContext(String jndiName, DataSource ds) throws Exception {

		ContextBinder.bind(jndiName, ds);

		logger.info("DataSource '" + jndiName + "' is bound");
	}

	private static DataSource createDS(String host, String userId, String password, String schema, Properties props) {

		String mysqlConnUrl = "jdbc:mysql://" + host + "/" + schema;

		String propStr = "";
		if (props != null && props.size() > 0) {
			StringBuilder sb = new StringBuilder();
			for (Entry<Object, Object> en : props.entrySet()) {
				sb.append("&" + en.getKey() + "=" + en.getValue());
			}

			propStr = sb.toString().substring(1);

			if (mysqlConnUrl.indexOf("?") == -1) {
				propStr = "?" + propStr;
			} else {
				propStr = "&" + propStr;
			}
			mysqlConnUrl += propStr;
		}

		logger.info("DataSource URL:'" + mysqlConnUrl + "'");

		MysqlConnectionPoolDataSource ds = new MysqlConnectionPoolDataSource();
		ds.setURL(mysqlConnUrl);
		ds.setUser(userId);
		ds.setPassword(password);

		return ds;
	}

}
